package com.qf.utils;

/**
 * @author zdl
 * @date 2025/3/11
 */

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;

public class SendMailUtil {

    // QQ 邮箱 SMTP 服务器地址
    private static final String SMTP_HOST = "smtp.qq.com";
    // QQ 邮箱 SMTP 服务器端口
    private static final int SMTP_PORT = 587;
    // 发件人邮箱地址
    private static final String FROM_EMAIL = "599936963@qq.com";
    // 发件人邮箱密码（授权码）
    private static final String FROM_EMAIL_PASSWORD = "qojnoslxcgbybcif";

    /**
     * 发送验证码到指定邮箱
     *
     * @param toEmail 收件人邮箱
     * @return 发送的验证码
     */
    public static String sendVerificationCode(String toEmail) {
        // 生成随机验证码
        String verificationCode = generateVerificationCode();

        // 邮件主题和内容
        String subject = "验证码";
        String content = "您的验证码是：" + verificationCode + "，请勿泄露给他人。";

        // 配置邮件服务器
        Properties props = new Properties();
        props.put("mail.smtp.host", SMTP_HOST);
        props.put("mail.smtp.port", SMTP_PORT);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");

        // 创建会话
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM_EMAIL, FROM_EMAIL_PASSWORD);
            }
        });

        try {
            // 创建邮件
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(FROM_EMAIL));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
            message.setSubject(subject);
            message.setText(content);

            // 发送邮件
            Transport.send(message);
            System.out.println("验证码已发送到 " + toEmail);
        } catch (MessagingException e) {
            e.printStackTrace();
            System.err.println("发送邮件失败: " + e.getMessage());
        }

        return verificationCode;
    }

    /**
     * 生成随机验证码
     *
     * @return 6位随机验证码
     */
    private static String generateVerificationCode() {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        return String.valueOf(code);
    }

    public static void main(String[] args) {
        // 测试发送验证码
        String toEmail = "2962777319@qq.com";
        String verificationCode = sendVerificationCode(toEmail);
        System.out.println("验证码: " + verificationCode);
    }
}
